/*
通过mutation间接更新state的多个方法的对象
 */
import {
  ARTICLES,
  ALL_CATEGORY_GOODS,
  GOODS,
  HOT_GOODS
} from './mutation-types'
import {
  reqArticlePage,
  reqCategoryAndGoods,
  reqGoodsById,
  reqHotGoods
} from '../api'
// import Store from '../api/store.js'

export default {
  async getArticlePage ({commit, state}, data) {
    // 发送异步ajax请求
    const result = await reqArticlePage(data)
    console.log('=============> actions.js -> getArticlePage', result)
    // 提交一个mutation
    if (result.code === 0) {
      const articles = result.data.page.list
      commit(ARTICLES, {articles})
    }
  },

  async getAllCategoryAndGoods ({commit, state}, callback) {
    // 发送异步ajax请求
    const result = await reqCategoryAndGoods()
    console.log('=============> actions.js -> getAllCategoryAndGoods', result)
    // 提交一个mutation
    if (result.code === 0) {
      const categoryAndGoods = result.data.list
      commit(ALL_CATEGORY_GOODS, {categoryAndGoods})
      // 数据更新了, 通知一下组件,这样写不会报错因为undefined&&任何值都是undefined
      callback && callback()
    }
  },

  async getGoodsById ({commit, state}, id) {
    // 发送异步ajax请求
    const result = await reqGoodsById(id)
    console.log('=============> actions.js -> getGoodsById', result)
    // 提交一个mutation
    if (result.code === 0) {
      const goods = result.data.data
      commit(GOODS, {goods})
    }
  },

  // 异步获取热销商品
  async getHotGoods ({commit, state}, callback) {
    // 发送异步ajax请求
    const result = await reqHotGoods()
    console.log('=============> actions.js -> getHotGoods', result)
    // 提交一个mutation
    if (result.code === 0) {
      const hotGoods = result.data.list
      commit(HOT_GOODS, {hotGoods})
      // 数据更新了, 通知一下组件,这样写不会报错因为undefined&&任何值都是undefined
      callback && callback()
    }
  }
}
